# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings
from django.template import Context
from django.template.loader import get_template

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.qr import make_code
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '248423419c61eb77': {
        # moopay  alipay-wap 2% 10-10000 zs
        # moopay  云闪付 1.6% 10-10000 zs
        'API_KEY': '3fabaa581b887b94e74a5cacca043d4f',
        'gateway': 'http://api.moopay88.com/wpay/api?do=CreateOrder',
        'query_gateway': 'http://api.moopay88.com/wpay/api?do=QueryMchOrder',
    },
    'fa781b293a934ed0': {  # moopay  alipay-扫码 2% 10-10000 zs
        'API_KEY': '0fa94d97bfc70368678afbc5357745a7',
        'gateway': 'http://api.mmpayss.com/wpay/api?do=CreateOrder',
        'query_gateway': 'http://api.mmpayss.com/wpay/api?do=QueryMchOrder',
    },
    '7df5372399c227b3': {  # moopay  alipay-扫码 2% 10-10000 zs
        'API_KEY': '8ab7d011c5d608e04878471f548095a6',
        'gateway': 'http://api.oldpays168.com/wpay/api?do=CreateOrder',
        'query_gateway': 'http://api.oldpays168.com/wpay/api?do=QueryMchOrder',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def generate_sign(parameter, key):
    s = ''
    key_list = ['cp_order_no', 'mch_id', 'notify_url', 'order_amount']
    sorted_dict = OrderedDict((k, parameter.get(k)) for k in key_list)
    _LOGGER.info("sorted_dict  is: %s", sorted_dict)
    for k in sorted_dict:
        if k != 'sign' and sorted_dict[k]:
            s += '%s=%s&' % (k, sorted_dict[k])
    s = s[:len(s) - 1]
    s += '%s' % key
    _LOGGER.info("moopay sign str: %s", s)
    return _gen_sign(s)


def generate_notify_sign(parameter, key):
    s = ''
    key_list = ['cp_order_no', 'goods_id', 'order_amount', 'order_uid', 'pay_amount']
    sorted_dict = OrderedDict((k, parameter.get(k)) for k in key_list)
    _LOGGER.info("sorted_dict  is: %s", sorted_dict)
    for k in sorted_dict:
        if sorted_dict[k]:
            s += '%s=%s&' % (k, sorted_dict[k])
    s = s[:len(s) - 1]
    s += '%s' % key
    _LOGGER.info("moopay notify sign str: %s", s)
    return _gen_sign(s)


def generate_query_sign(parameter, key):
    s = ''
    key_list = ['mch_id', 'cp_order_no', 'ts']
    sorted_dict = OrderedDict((k, parameter.get(k)) for k in key_list)
    _LOGGER.info("sorted_dict  is: %s", sorted_dict)
    for k in sorted_dict:
        if k != 'sign' and sorted_dict[k]:
            s += '%s=%s&' % (k, sorted_dict[k])
    s = s[:len(s) - 1]
    s += '%s' % key
    _LOGGER.info("moopay query sign str: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_notify_sign(params, key)
    if sign.lower() != calculated_sign.lower():
        _LOGGER.info("moopay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipay':
        return 2
    elif service == 'cloud_flash':
        return 4
    return 2


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('mch_id', app_id),
        ('cp_order_no', str(pay.id)),
        ('order_uid', str(pay.user_id)),
        ('order_amount', int(pay_amount * 100)),
        ('trade_type', _get_pay_type(service)),
        ('notify_url', '{}/pay/api/{}/moopay/{}/'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('goods_id', 'moopay'),
        ('goods_name', 'charge'),
        ('ip', _get_device_ip(info)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("moopay create: %s", json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/json'}
    response = requests.post(_get_gateway(app_id), data=json.dumps(parameter_dict), headers=headers, timeout=5)
    _LOGGER.info('moopay create rsp, %s', response.text)
    data = json.loads(response.text)['data']
    if service == 'cloud_flash':
        template_data = {'base64_img': make_code(data['qrcode']), 'amount': pay_amount,
                         'order_id': parameter_dict['cp_order_no'], 'due_time': int(time.time()) + 180}
        t = get_template('cloud_flash_moopay.html')
        html = t.render(Context(template_data))
        cache_id = redis_cache.save_html(pay.id, html)
        _LOGGER.info("moopay create_url: %s, pay.id: %s", settings.PAY_CACHE_URL + cache_id, pay.id)
        return {'charge_info': settings.PAY_CACHE_URL + cache_id}
    else:
        return {'charge_info': data['pay_url']}


# SUCCESS
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("moopay notify data:  %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['cp_order_no']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('moopay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_no = data['cp_order_no']
    total_fee = float(data['order_amount']) / 100.0
    extend = {
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    _LOGGER.info('moopay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
    order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
    # async notify
    async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('mch_id', app_id),
        ('cp_order_no', str(pay_order.id)),
        ('ts', int(time.time())),
    ))
    parameter_dict['sign'] = generate_query_sign(parameter_dict, api_key)
    data = json.dumps(parameter_dict)
    _LOGGER.info('moopay query data, %s' % data)
    headers = {'Content-Type': 'application/json'}
    response = requests.post(_get_query_gateway(app_id), data=json.dumps(data), headers=headers, timeout=5)
    _LOGGER.info('moopay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        _LOGGER.info("moopay query response body: %s", data)
        mch_id = pay_order.mch_id
        trade_status = str(data['retcode'])
        total_fee = float(pay_order.total_fee)
        trade_no = pay_order.id
        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }
        if trade_status == '0':
            check_channel_order(pay_id, total_fee, app_id)
            _LOGGER.info('moopay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
        else:
            raise ParamError('moopay query order %s' % str(data['retdesc']))
